/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useState } from 'react';
import { message, Spin } from 'antd';
import type { RcFile } from 'rc-upload/lib/interface';
import UploadWithCrypto from '@base/components/upload-width-crypto';
import type { UploadProps } from 'antd/es/upload/interface';

import { checkUpFiles } from './config';

type checkType = 'checkImg' | 'checkFile' | '';
interface KbUpload extends UploadProps {
  onCallBack: ({ url, fileName }: { url: string; fileName: string }) => void;
  children: React.ReactNode;
  checkType: checkType;
  multiple?: boolean;
  showUploadList?: boolean | any;
  api?: string;
  style?: React.CSSProperties;
  isLoading?: boolean;
  checkSize?: number;
}

const UploadImage: React.FC<KbUpload> = (props) => {
  const {
    onCallBack,
    children,
    api = '/Inn/uploadYtStationCode',
    checkType = '',
    isLoading,
    checkSize = 50,
    ...rest
  } = props;
  const [fileName, setFileName] = useState<string>('');
  const [loading, setLoading] = useState<boolean>(false);

  const checkFileSize = (file: RcFile) => {
    if (isLoading) {
      setLoading(true);
    }
    const { name } = file;
    setFileName(name);
    checkUpFiles(file, checkType, checkSize);
  };

  const onSuccess = (result: any) => {
    const { code, data, msg } = result;
    if (code == 0) {
      onCallBack({ url: data, fileName });
    } else {
      message.error(msg);
    }
    if (loading) {
      setLoading(false);
    }
  };

  return (
    <Spin spinning={loading}>
      <UploadWithCrypto
        action={api}
        listType='text'
        beforeUpload={checkFileSize}
        onSuccess={onSuccess}
        {...rest}
      >
        {children}
      </UploadWithCrypto>
    </Spin>
  );
};

UploadImage.defaultProps = {
  onCallBack: () => {},
  checkType: '',
  children: undefined,
  multiple: false,
  showUploadList: false,
  method: 'POST',
};

export default UploadImage;
